//
//  CJNativeAdapter.m
//  CJMobileAdapter
//
//  Created by ly on 2024/3/4.
//

#import "CJNativeAdapter.h"
#import "CJNativeCustomEvent.h"
#import "CJAdapterHeader.h"
#import "CJCommonTool.h"
#import "CJATTMBiddingManager.h"
#import "CJNativeRenderer.h"
#import "CJAdapterSetup.h"

@interface CJNativeAdapter()

@property (nonatomic, strong) CJNativeCustomEvent *customEvent;
@property (nonatomic, strong) CJNativeAd *nativeAd;

@end

@implementation CJNativeAdapter

-(instancetype) initWithNetworkCustomInfo:(NSDictionary*)serverInfo localInfo:(NSDictionary*)localInfo {
    if (self = [super init]) {
//        [CJAdapterSetup setupCJSDKWithAppId:@"appid"];
    }
    return self;
}

- (void)loadADWithInfo:(NSDictionary *)serverInfo localInfo:(NSDictionary *)localInfo completion:(void (^)(NSArray *, NSError *))completion {
    _customEvent = [[CJNativeCustomEvent alloc] initWithInfo:serverInfo localInfo:localInfo];
    _customEvent.requestCompletionBlock = completion;
    CJATTMBiddingRequest *request = [[CJATTMBiddingManager sharedInstance] getRequestItemWithUnitID:serverInfo[@"unitid"]];
    if (request) {
        [request.assets setValue:_customEvent forKey:kATAdAssetsCustomEventKey];
        if (request.customObject != nil) { // load secced
            self.nativeAd = request.customObject;
            self.nativeAd.delegate = _customEvent;
            completion(request.assets, nil);
        } else { // fail
            NSError *error = [NSError errorWithDomain:ATADLoadingErrorDomain code:ATAdErrorCodeThirdPartySDKNotImportedProperly userInfo:@{NSLocalizedDescriptionKey:@"AT has failed to load native.", NSLocalizedFailureReasonErrorKey:@"It took too long to load placement stragety."}];
            [_customEvent trackNativeAdLoadFailed:error];
        }
        [[CJATTMBiddingManager sharedInstance] removeRequestItmeWithUnitID:serverInfo[@"unitid"]];
    } else {
        [self loadAdNativeExpressAdWithInfo:serverInfo localInfo:localInfo completion:completion];
    }
}

// 模板渲染
- (void)loadAdNativeExpressAdWithInfo:(NSDictionary *)serverInfo localInfo:(NSDictionary *)localInfo completion:(void (^)(NSArray *, NSError *))completion {
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 0);
    if ([serverInfo valueForKey:kATExtraInfoNativeAdSizeKey]) {
        size = [[serverInfo valueForKey:kATExtraInfoNativeAdSizeKey] CGSizeValue];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        self.nativeAd = [[CJNativeAd alloc] initWithSlotId: serverInfo[@"unitid"] size:size rootViewController:[CJCommonTool currentRootController]];
        self.nativeAd.delegate = self.customEvent;
        self.customEvent.nativeAd = self.nativeAd;
        [self.nativeAd loadAdData:1];
    });
}


+ (void)bidRequestWithPlacementModel:(ATPlacementModel *)placementModel unitGroupModel:(ATUnitGroupModel *)unitGroupModel info:(NSDictionary *)info completion:(void(^)(ATBidInfo *bidInfo, NSError *error))completion {
    if (NSClassFromString(@"CJADManager") == nil) {
        if (completion != nil) { completion( nil, [NSError errorWithDomain:@"com.ubix.mediation.ios" code:1 userInfo:@{NSLocalizedDescriptionKey:@"Bid request has failed", NSLocalizedFailureReasonErrorKey:@"CJAD is not imported"}]); }
        return;
    }
    [CJADManager openDebugLog];
    [CJADManager configure:info[@"appid"]];
    CJATTMBiddingManager *biddingManage = [CJATTMBiddingManager sharedInstance];
    CJATTMBiddingRequest *request = [CJATTMBiddingRequest new];
    request.unitGroup = unitGroupModel;
    request.placementID = placementModel.placementID;
    request.bidCompletion = completion;
    request.unitID = info[@"unitid"];
    request.extraInfo = info;
    request.adType = ESCAdFormatNative;
    CGSize size = CGSizeMake([UIScreen mainScreen].bounds.size.width, 0);
    if ([info valueForKey:kATExtraInfoNativeAdSizeKey]) {
        size = [[info valueForKey:kATExtraInfoNativeAdSizeKey] CGSizeValue];
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        CJNativeAd *nativeAd = [[CJNativeAd alloc] initWithSlotId: info[@"unitid"] size:size rootViewController:[CJCommonTool currentRootController]];
        request.customObject = nativeAd;
        [biddingManage startWithRequestItem:request];
        [nativeAd loadAdData:1];
    });
}


+ (void)sendWinnerNotifyWithCustomObject:(id)customObject secondPrice:(NSString*)price userInfo:(NSDictionary<NSString *, NSString *> *)userInfo {
    CJSplashAd *splashAd = (CJSplashAd *)customObject;
    NSLog(@"比价成功");
}

+ (void)sendLossNotifyWithCustomObject:(nonnull id)customObject lossType:(ATBiddingLossType)lossType winPrice:(nonnull NSString *)price userInfo:(NSDictionary *)userInfo {
    NSLog(@"比价失败");
}


+ (Class)rendererClass {
    return [CJNativeRenderer class];
}

@end
